﻿using System;
using System.Linq;
using System.Collections.Specialized;
using System.Collections;

namespace IdeaNMR.Shared.Utils
{
    public static class OrderedDictionaryExtensions
    {
        /// <summary>
        /// Switches the content of two entries with indexes i and j, respectively.
        /// </summary>
        /// <param name="i">Index of first entry.</param>
        /// <param name="j">Index of second entry</param>
        /// <exception cref="ArgumentOutOfRangeException">If i or j are greater than the actual number of elements in dictionary.</exception>
        public static void SwitchTwo(this OrderedDictionary dict, int i, int j)
        {
            int Capacity = dict.Count;
            if (i == j) return;
            if (i >= Capacity) throw new ArgumentOutOfRangeException("i", i, string.Format("The index is greater than the actual number of elements '{0}' in the dictionary.", Capacity));
            if (j >= Capacity) throw new ArgumentOutOfRangeException("j", j, string.Format("The index is greater than the actual number of elements '{0}' in the dictionary.", Capacity));

            if (i > j)
            {
                int temp;
                temp = i;
                i = j;
                j = temp;
            }

            // Arrays of Keys and values are created
            object[] myKeys = new object[Capacity]; // Get an array of Keys
            dict.Keys.CopyTo(myKeys, 0);
            object[] myValues = new object[Capacity];
            dict.Values.CopyTo(myValues, 0);

            // Values to switch are stored in variables
            DictionaryEntry iEntry = new DictionaryEntry(myKeys[i], myValues[i]);
            DictionaryEntry jEntry = new DictionaryEntry(myKeys[j], myValues[j]);

            // Removing entries
            dict.Remove(iEntry.Key);
            dict.Remove(jEntry.Key);

            //Inserting values in switched order; i must go first, otherwise position of j will be shifted +1
            dict.Insert(i, jEntry.Key, jEntry.Value);
            dict.Insert(j, iEntry.Key, iEntry.Value);
        }

        /// <summary>
        /// Function to get the index of entry by its key.
        /// </summary>
        /// <param name="key"></param>
        /// <returns> Int Index if key found and -1 if not found.</returns>
        public static int GetIndexOf(this OrderedDictionary dict, object key)
        {
            if (!dict.Contains(key)) return -1; // If key is not in Dictionary - return -1

            int Capacity = dict.Count;
            object[] myKeys = new object[Capacity]; // Get an array of Keys

            dict.Keys.CopyTo(myKeys, 0);
            for (int i = 0; i < Capacity; i++)
            {
                if (myKeys[i].Equals(key)) return i;
            }
            return -1;
        }
    }
}
